package com.czh.intelligentoj.judge.codesandbox.impl;


import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.czh.intelligentoj.common.ErrorCode;
import com.czh.intelligentoj.common.SignUtils;
import com.czh.intelligentoj.exception.BusinessException;
import com.czh.intelligentoj.judge.codesandbox.CodeSandbox;
import com.czh.intelligentoj.judge.codesandbox.model.ExecuteCodeRequest;
import com.czh.intelligentoj.judge.codesandbox.model.ExecuteCodeResponse;
import org.apache.commons.lang3.StringUtils;
import java.util.HashMap;

/*
 * ClassName: RemoteCodeSandbox
 * Package: com.czh.intelligentoj.judge.codesandbox.impl
 * Description:
 *          远程API调用代码沙箱
 * @Author: CZH
 * @Create: 2025
 */
public class RemoteCodeSandbox implements CodeSandbox {

    private static final String AUTH_REQUEST_HEADER = "authorization";

    private static final String AUTH_REQUEST_SECRET = "hj8gv8F88g";

    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest executeCodeRequest) {
        System.out.println("远程沙箱~");
        String json = JSONUtil.toJsonStr(executeCodeRequest);
        //用户认证
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("accessKey", AUTH_REQUEST_HEADER);
//        hashMap.put("nonce", RandomUtil.randomNumbers(5));
        hashMap.put("body", json);
        hashMap.put("timestamp", String.valueOf(System.currentTimeMillis() / 1000));
        hashMap.put("sign", SignUtils.getSign(json,AUTH_REQUEST_SECRET));
        String url = "http://localhost:8090/sandbox";
        String body = HttpUtil.createPost(url)
                .addHeaders(hashMap)
                .body(json)
                .execute()
                .body();
        if(StringUtils.isBlank(body)){
            throw new BusinessException(ErrorCode.API_REQUEST_ERROR,"远程沙箱错误：" + body);
        }
        return JSONUtil.toBean(body, ExecuteCodeResponse.class);
    }


}
